const util = require('util');
const debug = util.debuglog('oil-game:sync:user');

const {syncBoxMemData, syncBox} = require("../../servers/box/lib/cache");
const {syncUpgrade} = require("../../servers/upgrade/lib/cache");
//const {syncLuckDrawData} = require("../../servers/luckDraw/lib/cache");
const {syncExchangeFrom} = require("../../servers/exchange/lib/cache");
const {syncExchangeFrom: syncExchangeEssenceFrom} = require("../../servers/exchangeEssence/lib/cache");


var User = require('../../servers/login/lib/userSchema');
var Level = require('../../domain/level');
var ExchangeFrom = require('../../servers/exchange/lib/exchangeSchema');
var async = require('async');

module.exports = {
    updateUser: function (client, userInfo, cb) {
        const {uid} = userInfo;
        userInfo.last_logout_time = new Date().valueOf();
        debug("同步用户信息到数据库 %s", JSON.stringify(userInfo));
        User.updateOne({uid}, userInfo, function (err, data) {
            if (!!cb && typeof cb == 'function') {
                cb(!!err);
            }
        });
    },
    updateOpenChest: async function (client, userInfo, cb) {
        let {uid, ownOpenBox, waitOpenBox} = userInfo
        //没有数据，不需要同步
        if (!(Array.isArray(ownOpenBox) && Array.isArray(waitOpenBox))) {
            debug(" uid = %s  ownOpenBox = %s  waitOpenBox = %s  同步宝箱信息到服务器，不需要同步，直接退出", uid, JSON.stringify(ownOpenBox), JSON.stringify(waitOpenBox));
            return cb(true);
        }
        debug(" uid = %s  ownOpenBox = %s  waitOpenBox = %s  同步宝箱信息到服务器", uid, JSON.stringify(ownOpenBox), JSON.stringify(waitOpenBox));
        try {
            await syncBoxMemData(uid, ownOpenBox, waitOpenBox);
            cb(true);
        } catch (err) {
            console.error(err);
            cb(err);
        }
    },
    syncBox: async function (client, userInfo, cb) {    //同步宝箱数据
        try {
            await syncBox(userInfo);
            cb(true);
        } catch (err) {
            console.error(err);
            cb(err);
        }
    },
    updateExchange: async function (client, userInfo, cb) {
        let {exchange} = userInfo;
        debug("同步交易所信息到服务器 %s", JSON.stringify(exchange));
        if (!exchange) {
            debug("同步交易所信息到服务器，交易所为空，直接退出");
            return cb(true);
        }
        try {
            //保存交易所信息
            await syncExchangeFrom(exchange);
            cb(true);
        } catch (err) {
            debug("同步交易所信息到服务器异常 %s", JSON.stringify(err));
            cb(err);
        }
    },
    exchangeEssenceSave: async function (client, userInfo, cb) {
        let {exchangeEssence} = userInfo;
        debug("同步精华交易所信息到服务器 %s", JSON.stringify(exchangeEssence));
        if (!exchangeEssence) {
            debug("同步精华交易所信息到服务器，交易所为空，直接退出");
            return cb(true);
        }
        try {
            //保存交易所信息
            await syncExchangeEssenceFrom(exchangeEssence);
            cb(true);
        } catch (err) {
            debug("同步精华交易所信息到服务器异常 %s", JSON.stringify(err));
            cb(err);
        }
    },
    updateUpgrade: async function (client, userInfo, cb) {
        let {upgrade} = userInfo;
        debug("同步升级信息到服务器 %s", JSON.stringify(upgrade));
        if (!upgrade) {
            debug("upgrade = %s  同步升级信息到服务器，升级信息为空，直接退出", JSON.stringify(upgrade));
            return cb(true);
        }
        try {
            //保存升级信息
            await syncUpgrade(upgrade);
            cb(true);
        } catch (err) {
            debug("同步升级信息到服务器异常 %s", JSON.stringify(err));
            cb(err);
        }
    },
    updateSignIn: async function (client, userInfo, cb) {
        let {signIn} = userInfo;
        debug("同步签到信息到服务器 %s", JSON.stringify(signIn));
        if (!signIn) {
            debug("upgrade = %s  同步签到信息到服务器，签到信息为空，直接退出", JSON.stringify(signIn));
            return cb(true);
        }
        try {
            //保存升级信息
            await syncSignIn(signIn);
            cb(true);
        } catch (err) {
            debug("同步签到信息到服务器异常 %s", JSON.stringify(err));
            cb(err);
        }
    },
    luckDrawSave: async function (client, userInfo, cb) {
        let {luckDraw} = userInfo;
        debug("同步幸运抽奖信息到服务器 %s", JSON.stringify(luckDraw));
        if (!luckDraw) {
            debug("luckDraw = %s  同步幸运抽奖信息到服务器，签到信息为空，直接退出", JSON.stringify(luckDraw));
            return cb(true);
        }
        try {
            //保存幸运抽奖信息
            //await syncLuckDrawData(luckDraw);
            cb(true);
        } catch (err) {
            debug("同步幸运抽奖信息到服务器异常 %s", JSON.stringify(err));
            cb(err);
        }
    },
    updateMap: function (client, userInfo, cb) {
        let uid = userInfo.uid;
        let levelInfo = userInfo.levelInfo;
        if (!levelInfo) {
            return cb();
        }
        async.each(levelInfo, function (item, cb) {
            Level.findOne({uid: uid, level_num: item['level_num']}, function (err, level) {
                if (level) { //有数据更新
                    Level.updateOne({
                        uid: uid,
                        level_num: item['level_num']
                    }, item, function (err, data) {
                        if (!!cb && typeof cb == 'function') {
                            return cb();
                        }
                    });
                } else { //没数据插入
                    var newLevel = new Level({
                        uid: uid,
                        level_num: item['level_num'],
                        product: item['product'],
                        floor_level: item['floor_level'],
                        upgrade_need: item['upgrade_need']
                    });
                    newLevel.save(function (err) {
                        if (!!err) {
                            console.log("updateMap err: ", err)
                        }
                        cb();
                    });
                }
            });
        }, function (err) {
            cb();
        });
    },
    rankQuery: function (cb) {
        User.find({jewel: {$gt: 0}}).limit(100).sort({
            jewel: -1,
            coins: -1
        }).select('uid title avatar nickname current_level jewel').exec(cb);
    },
    individualRank: function (uid, total_oil, cb) {
        async.waterfall([
            function (callback) {
                User.countDocuments().where({uid: {$ne: uid}}).where({total_oil: {$gt: total_oil}}).exec(function (err, rank) {
                    callback(err, rank)
                });
            }, function (num, callback) {
                User.countDocuments().where({uid: {$ne: uid}}).where({total_oil: total_oil}).exec(function (err, rank) {
                    callback(err, parseInt(num) + parseInt(rank));
                });
            }
        ], function (err, result) {
            cb(err, result)
        });
    },
    //用户石油排行榜
    oilRank(cb) {
        User.find({total_oil: {$gt: -1}}).limit(100).sort({
            total_oil: -1
        }).select('uid title avatar nickname total_oil depth_level contact_info phone').exec(cb);
    }
};
